package com.showsu.editor.utils.remote;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.showsu.editor.entity.remote.WhoseCardVideoDetailResp;
import com.showsu.editor.enums.SuccessEnum;
import com.showsu.editor.service.IRemoteInterfaceRecordService;
import com.showsu.editor.service.IRemoteInterfaceWarnSmsRecordService;
import com.showsu.editor.utils.Constant;
import com.showsu.editor.utils.HttpClientUtil;
import com.showsu.editor.utils.RetryUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * @Author: William
 * @Description: douyin/tiktok 数据请求接口
 * https://api.tikhub.io/#/Authorization/login_for_access_token_user_login_post
 * @Date: Created in 11:41 上午 2023/4/10
 * @Modified By:
 */
@Slf4j
@Component
public class TikhubUtil {

//    @Value("${portal.tikhubAPI.url}")
//    private String tikhubAPIUrl;
//
//    @Value("${portal.tikhubAPI.key}")
//    private String tikhubAPIKey;

    private static final String proxyUrl = "https://auto.showsu.cn/th";
    private static final String proxyToken = "B5BB8B61C7F4C3070A27D9B9BF9AFA7B";

    private static Map<String, String> headers = new HashMap<>();
    static {
        headers.put("Content-type", "application/json; charset=utf-8");
        headers.put("Connection", "keep-alive");
    }

    /**
     * 最多重试次数
     */
    private static final int RETRY_MAX_COUNT = 3;

    /**
     * 重试等待间隔
     */
    private static final int RETRY_WAIT_TIME = 1500;

    private static final Integer pageSize20 = 20;
    private static final Integer pageSize30 = 30;
    private static final Integer pageSize50 = 50;
    private static final Integer totalLimit = 60;

    @Autowired
    private IRemoteInterfaceRecordService remoteInterfaceRecordService;

    @Autowired
    private IRemoteInterfaceWarnSmsRecordService remoteInterfaceWarnSmsRecordService;


    /**
     * 查询抖音视频/图文详情-通过香港的服务器
     * @param awemeId
     * @return
     */
    public WhoseCardVideoDetailResp getDyVideoDetailByProxy(String awemeId, Long interfaceId) {
        if (StringUtils.isBlank(awemeId)) {
            return null;
        }
        WhoseCardVideoDetailResp result = null;
        Type type = new TypeToken<WhoseCardVideoDetailResp>(){}.getType();
        Gson gson = new Gson();
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("token", proxyToken);
            params.put("awemeId", awemeId);
            String response = RetryUtils.retry(new Callable<String>() {
                @Override
                public String call() {
                    try {
                        long start = System.currentTimeMillis();
                        String responseInner = HttpUtil.post(proxyUrl + "/dy/video/detail", JSON.toJSONString(params), Constant.defaultTimeOut);
                        log.info("TikhubUtil查询dy视频详情-走代理-响应耗时:{}-awemeId:{}", System.currentTimeMillis() - start, awemeId);
                        if (StringUtils.isBlank(responseInner)) {
                            return "";
                        }
                        JSONObject res = JSONObject.parseObject(responseInner);
                        if (res.get("data") == null || "error".equals(res.getString("data"))) {
                            return "";
                        }
                        WhoseCardVideoDetailResp temp = gson.fromJson(res.getString("data"), type);
                        if (temp == null || (temp.getCode() != null && temp.getCode() != 200)) {
                            remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                            return "";
                        }
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                        return responseInner;
                    } catch (Exception e) {
                        return "";
                    }
                }
            }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
            if (StringUtils.isBlank(response)) {
                remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId, new StringBuilder("awemeId=").append(awemeId).toString());
                return null;
            }
            if (StringUtils.isNotBlank(response)) {
                JSONObject res = JSONObject.parseObject(response);
                result = gson.fromJson(res.getString("data"), type);
                result.setResult(result.getData());
            }
        } catch (Exception e) {
            log.error("TikhubUtil.getDyVideoDetailByProxy(String) error", e);
        }
        return result;
    }

}
